package com.tlm.cloudzuul;

import com.google.common.util.concurrent.RateLimiter;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.FORM_BODY_WRAPPER_FILTER_ORDER;

@Component
public class PreFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return "PRE_TYPE";
    }

    @Override
    public int filterOrder() {//过略级别
        return FORM_BODY_WRAPPER_FILTER_ORDER;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    private static RateLimiter rateLimiter = RateLimiter.create(1);//声明令牌桶，每秒放多少个令牌
    @Override
    public Object run() throws ZuulException {
        //要走的方法
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        //获取get资源
        HttpServletRequest request = requestAttributes.getRequest();
        //请求类型
        String method = request.getMethod();//请求类型
        String requestURI = request.getRequestURI();//请求地址
        String token =  request.getParameter("token");//某个参数
//        log.info("请求类型:"+method);
//        log.info("请求地址:"+requestURI);
        System.out.println(method);
        System.out.println(requestURI);
        System.out.println(token);
        //限流
        if (!rateLimiter.tryAcquire()){
            throw new ZuulException("错误111",550,"错误22");
        }
        //鉴权-鉴定权限
        //1.是否登陆了
        //2.查询出你的权限，允许你去访问那个接口
        if(token.equals("是否有效")){
            return "跳转到登录页面";
        }
//        2.查询出你的权限，允许你去访问哪个接口
//        有一张表，权限-接口对应表
        //用户发送请求，查询用户对应的权限接口，比对需要请求的接口，如果有允许访问，如果没有不允许访问。
        return null;
    }
}
